package config

import (
	"io"
	"io/ioutil"
	"path"
)

const (
	JSONCONFIG = ".json"
	INICONFIG = ".ini"
	YAMLCONFIG = ".yaml"
	XMLCONFIG = ".xml"
	TOMLCONFIG = ".toml"
)

type File interface {
	Unmarshal(v interface{}) error
	Marshal(v interface{}) error
	io.ReadWriter
}


func openFile(fileName string) (fp File,err error) {
	bytes,err := ioutil.ReadFile(fileName)
	if err != nil {
		return nil,newError(err.Error())
	}

	switch path.Ext(fileName) {
	case TOMLCONFIG:
		fp = &tomlFile{
			name:fileName,
		}
	case JSONCONFIG:
		fp = &jsonFile{
			name:fileName,
		}
	default:
		return nil, newError("goose only support configure of '.json .xml .ini .yaml .toml'")
	}
	_,err = fp.Write(bytes)
	if err != nil {
		return nil,withError(err,"write data failed")
	}
	return fp,nil
}

type buffer []byte

func (buf *buffer) Write(b []byte) (n int,err error) {
	*buf = make([]byte,len(b))
	n = copy(*buf,b)
	return
}

func (buf *buffer) Read (b []byte) (n int,err error) {
	if cap(b) < len(*buf) {
		return len(*buf),newError("param::b must has the more cap count than buffer's")
	}
	n = copy(b,*buf)
	return
}

// 实例化一个配置文件，用于创建不同的配置文件格式
func NewConfigureFile(fileName string) File {
	switch path.Ext(fileName) {
	case JSONCONFIG:
		return &jsonFile{name:fileName}
	case TOMLCONFIG:
		return &tomlFile{name:fileName}
	default:
		return nil
	}
}